<?php

  global $mosUser, $mainframe, $message;

  // -- webMS Modification --
  // Ensure a valid runtime environment or die
  if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

  // -- webMS Modification --
  // Check if osCommerce environment is already loaded
  if (defined( '_OSCOMMERCE_LOADED' )) {
    if (!DB_SHARED) {
      // Reconnect to osCommerce Database
      tep_db_connect() or die('Unable to connect to database server!');
    }
    // Load osCommerce Globals for Boxes
    global $category_links, $languages_id, $catID, $catID_array, $current_category_id;
    global $request_type, $lng, $cart, $currencies, $language, $navigation, $breadcrumb;
global $sess, $mm_action_url, $mosConfig_lang;
           
  } else {
    // Load osCommerce Environment for the First Time
    require('components/'.$option.'/includes/application_top.php');
  }

if (function_exists('josSpoofValue')) {
$validate = josSpoofValue(1);
}

if (class_exists( 'JConfig' )){
$loginlink =  'index.php?option=com_user&amp;task=login';

	// Return URL
	$uri = JFactory::getURI();
	$url = $uri->toString();
	$returnurl = base64_encode( $url );
	$lostpasslink = sefReltoAbs('index.php?option=com_user&view=reset');

	// Set the validation value
	$validate = JUtility::getToken();
	}


if ($mosUser['id'] != '') {
tep_redirect($mosConfig_live_site.'/index.php?option=com_oscommerce&osMod=create_account');
}

  require(DIR_WS_LANGUAGES . $language . '/' . $osMod . '.php');

// redirect the customer to a friendly cookie-must-be-enabled page if cookies are disabled (or the session has not started)
  if ($session_started == false) {
    tep_redirect(tep_href_link(FILENAME_COOKIE_USAGE));
  }

  $error = false;
  if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'process')) {

    $password = tep_db_prepare_input($_REQUEST['password']);


    if ($password) {
	if (isset($_REQUEST['lvalue'])) {
		if ($_REQUEST['ltype'] == '1') {
			$email_address = tep_db_prepare_input($_REQUEST['lvalue']);
			} else {
			$username = tep_db_prepare_input($_REQUEST['lvalue']);
			}
	}else{
      // -- Prepare Variables --------------------------------------------------------
      $email_address = tep_db_prepare_input($_REQUEST['email_address']);
      $username = tep_db_prepare_input($_REQUEST['username']);
}

$passwd = trim( $_POST['password'] );
      //$passwd   = trim( mosGetParam( $_POST, 'password', '' ) );
      $passwd   = md5( $passwd );
      $userData = null;

      // -- Login Mambo --------------------------------------------------------------
      if (!$username && $email_address) {
        $userData = mos_get_user( $email_address );
        $username = $userData->username;
        
      }
      

      if ( $error == false ) {
        if ($username && $passwd) {
          if ( !$userData ) {
            // Load User Data to confirm existance and check handle Admin Block and Activation
            $database->setQuery( "SELECT * FROM #__users WHERE username='$username'" );
            
            //ok an issue is here -> joomla 1.5 vs joomla 1.0
            //if joomla 1.5 use:
            if(class_exists( 'JConfig' ) ) {
            $userData = $database->loadObject();
            }else{
            $database->loadObject($userData);
            }
            
          
          }
          if ( $userData->block && $userData->activation ) {
            $error = true;
            $messageStack->add('login', TEXT_LOGIN_WAITACT);
          } elseif ( $userData->block ) {
            $error = true;
            $messageStack->add('login', TEXT_LOGIN_BLOCKED);
          } elseif ( $userData ) {
            $_POST['username'] = $username;
            $_POST['passwd']   = $password;
             
             if(class_exists('JRequest')){
             
             global $mainframe;
$credentials = array();
		$credentials['username'] = JRequest::getVar('username', '', 'method', 'username');
		$credentials['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
		$reser = $mainframe->login($credentials);
		print_r($reser);
		 osc_match_mos_user($userData->id);
		
		
	 if (sizeof($navigation->snapshot) > 0) {
                $origin_href = tep_href_link($navigation->snapshot['page'],
                                              tep_array_to_string($navigation->snapshot['get'],
                                              array(tep_session_name())),
                                              $navigation->snapshot['mode']
                                              );
                $navigation->clear_snapshot();
                tep_redirect($origin_href);
              } else {
		tep_redirect(tep_href_link(FILENAME_ACCOUNT));
		}
		}else{
		
            $mainframe->login();
            }
            
            if ( $mainframe->_session->username ) {
              osc_match_mos_user( $mainframe->_session->userid );
              if (sizeof($navigation->snapshot) > 0) {
                $origin_href = tep_href_link($navigation->snapshot['page'],
                                              tep_array_to_string($navigation->snapshot['get'],
                                              array(tep_session_name())),
                                              $navigation->snapshot['mode']
                                              );
                $navigation->clear_snapshot();
                tep_redirect($origin_href);
              } else {
                tep_redirect(tep_href_link(FILENAME_ACCOUNT));
              }
            }
          } else {
            $error = true;
            $messageStack->add('login', TEXT_LOGIN_ERROR);
          }
        } else {
          $error = true;
          $messageStack->add('login', TEXT_LOGIN_ERROR);
        }
      }

      // osCommerce Login Procedures Removed
      // Source can be found in REMOVED_SOURCE section 1
    } else {
  
      $error = true;
      $messageStack->add('login', TEXT_LOGIN_NOPASS);
    }
  }

  $breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_LOGIN, '', 'SSL'));
?>
<script language="javascript"><!--
function session_win() {
  window.open("<?php echo tep_href_link(FILENAME_INFO_SHOPPING_CART,'popup'); ?>","info_shopping_cart","height=460,width=430,toolbar=no,statusbar=no,scrollbars=yes").focus();
}
//--></script>
<?php require(DIR_WS_INCLUDES . 'header.php'); 
//$a['form'] = tep_draw_form('login', tep_href_link(FILENAME_LOGIN, 'action=process', 'SSL'));


$a['form'] = tep_draw_form('login', tep_href_link(FILENAME_LOGIN, tep_get_all_get_params(array('action')) . 'action=process', 'SSL'));

$a['heading'] = HEADING_TITLE;
$a['heading_img'] = tep_image(DIR_WS_IMAGES . 'table_background_login.gif', HEADING_TITLE, HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT);
$a['headiscust'] = HEADING_RETURNING_CUSTOMER;
$a['visitorcart'] = TEXT_VISITORS_CART;
$a['retcust'] = TEXT_RETURNING_CUSTOMER;
$a['username'] = ENTRY_USERNAME;
$a['username_input'] = tep_draw_input_field('username');
$a['password'] = ENTRY_PASSWORD;
$a['password_input'] = tep_draw_password_field('password');
$a['forgotpassword'] = '<a href="' . tep_href_link(FILENAME_PASSWORD_FORGOTTEN, '', 'SSL') . '">' . TEXT_PASSWORD_FORGOTTEN . '</a>';
$a['button_submit'] = tep_image_submit('button_login.gif', IMAGE_BUTTON_LOGIN);
$a['newcust'] = HEADING_NEW_CUSTOMER;
$a['newcusttext'] = TEXT_NEW_CUSTOMER . '<br><br>' . TEXT_NEW_CUSTOMER_INTRODUCTION;
$a['button_continue'] = '<a href="'.tep_href_link(FILENAME_CREATE_ACCOUNT, '', 'SSL').'">'.tep_image_button('button_continue.gif',IMAGE_BUTTON_CONTINUE,IMAGE_BUTTON_CONTINUE).'</a>';
require(WS_TEMPLATES . E_TEMPLATE_FOLDER . '/'.$osMod.'.html');
require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->

<?php
  require(DIR_WS_INCLUDES . 'application_bottom.php');

  // -- webMS Modification --
  // reset the Mambo Database connection (stomped by osCommerce Connection)
  if (!DB_SHARED) {
    global $database, $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix;
    $database = new database( $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix );
  }
 ?>
